<?php


namespace App\Http\Controllers;


use App\Models\User;
use EasyWeChat\Kernel\Exceptions\InvalidArgumentException;
use EasyWeChat\MiniApp\Application;
use EasyWeChat\MiniApp\Utils;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use QCloud\COSSTS\Sts;
use function EasyWeChat\MiniApp\getUtils;

class MiniAppController extends Controller
{

    public function isLogin(){
        return Json(1,'OK111111111111');
    }

    public function auth()
    {

        $code=request()->post('code');
        Log::info("获取参数：".json_encode(request()->post()));
        Log::info("获取参数header：".json_encode(request()->header()));
        $rawData = request()->post('rawData');
        $iv = request()->post('iv');
        $encryptedData = request()->post('encryptedData');
        $config = [
            'app_id' => env('MINIAPP_APP_ID'),
            'secret' =>env('MINIAPP_SECRET'),
        ];
        try {
            $app = new Application($config);
            $utils=(new Utils($app));
            $response = $utils->codeToSession($code);
            if(empty($response)){
                return Json(0,'登录失败,请联系客服#001') ;
            }
            $user=User::query()->where('openid','=',$response['openid'])->first();
            if(empty($user)){
                $user=new User();
                $user->openid=$response['openid'];
            }
            $user->session_key=$response['session_key'];
            $user->save();
            $token=md5($response['openid'].$response['session_key']);
            Cache::put('w_user:'.$token,serialize($user));
            return  Json(1,'ok',[
                'token'=>$token,
                'user'=>[
                    'id'=>$user->id,
                    'name'=>empty($user->name)?"":$user->name,
                    'avatar'=>empty($user->avatar)?"":$user->avatar,
                ]
            ]);
        } catch (InvalidArgumentException $e) {
            return  Json(0,$e->getMessage());
        } catch (\Exception $e) {
            Log::error("登录失败：".$e->getMessage());
            return  Json(0,'登录失败,请联系客服#003');
        }

    }

    //更新用户信息
    public function update(){
        $nickName=request()->input('nickName');
        $avatarUrl=request()->input('avatarUrl');
        $user=User::query()->where('id','=',Auth::id())->first();
        $user->name=$nickName;
        $user->avatar=$avatarUrl;
        $user->save();
        return Json(1,'ok',[
            'id'=>$user->id,
            'name'=>$user->name,
            'avatar'=>$user->avatar,
        ]);
    }


    /**
     *
     */
    public function cos(){
        $sts = new STS();
            // 配置参数
        $config = array(
            'url' => 'https://sts.tencentcloudapi.com/',
            'domain' => 'sts.tencentcloudapi.com',
            'proxy' => '',
            'secretId' => env('COSV5_SECRET_ID'), // 固定密钥
            'secretKey' => env('COSV5_SECRET_KEY'), // 固定密钥
            'bucket' => env('COSV5_BUCKET'), // 换成你的 bucket
            'region' => env('COSV5_REGION'), // 换成 bucket 所在园区
            'durationSeconds' => 1800, // 密钥有效期
            'allowPrefix' => '*', // 这里改成允许的路径前缀，可以根据自己网站的用户登录态判断允许上传的目录，例子：* 或者 a/* 或者 a.jpg
            // 密钥的权限列表。简单上传需要以下的权限，其他权限列表请看 https://cloud.tencent.com/document/product/436/31923
            'allowActions' => array (
                // 简单上传
                'name/cos:PutObject',
                'name/cos:PostObject',
                'name/cos:DeleteObject',
            )
        );
        // 获取临时密钥，计算签名
        $tempKeys = $sts->getTempKeys($config);
        return  Json(1,'ok',$tempKeys);
    }

}
